//
//  JsonHelper.m
//  StoneBingCn
//
//  Created by REACNN on 13-12-20.
//  Copyright (c) 2013年 REACNN.COM. All rights reserved.
//

#import "JSONHelper.h"

@implementation JSONHelper

+(NSArray *)DeserializerArray:(NSString *)jsonstr
{
    CJSONDeserializer *theDeserializer = [CJSONDeserializer deserializer];
    theDeserializer.options |= kJSONDeserializationOptions_AllowFragments;
    
    NSError *error = Nil;
    NSData *data = [jsonstr dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *datalist = [theDeserializer deserializeAsArray:data error:&error];
    
    if (error) {
        NSLog(@"JSONHelper , DeserializerArray Error : %@ ,jsonstr : %@ ",error,jsonstr);
        return nil;
    }
    else{
        return datalist;
    }
}

+(NSDictionary *)DeserializerDictionary:(NSString *)jsonstr
{
    CJSONDeserializer *theDeserializer = [CJSONDeserializer deserializer];
    theDeserializer.options |= kJSONDeserializationOptions_AllowFragments;
    
    NSError *error = Nil;
    NSData *data = [jsonstr dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *datalist = [theDeserializer deserializeAsDictionary:data error:&error];
    
    if (error) {
        NSLog(@"JSONHelper , DeserializerDictionary Error : %@ ,jsonstr : %@ ",error,jsonstr);
        return nil;
    }
    else{
        return datalist;
    }
}

+(id)Deserializer:(NSString *)jsonstr
{
    CJSONDeserializer *theDeserializer = [CJSONDeserializer deserializer];
    theDeserializer.options |= kJSONDeserializationOptions_AllowFragments;
    
    NSError *error = Nil;
    NSData *data = [jsonstr dataUsingEncoding:NSUTF8StringEncoding];
    
    if ([jsonstr hasPrefix:@"{"]) {
        
        NSArray *datalist = [theDeserializer deserializeAsArray:data error:&error];
        if (error) {
            NSLog(@"%@",error);
            return nil;
        }
        else{
            return datalist;
        }
    }
    else if([jsonstr hasPrefix:@"["])
    {
        NSDictionary *datalist = [theDeserializer deserializeAsDictionary:data error:&error];
        if (error) {
            NSLog(@"%@",error);
            return nil;
        }
        else{
            return datalist;
        }
    }
    else
    {
        NSLog(@"未知的json格式，无法解析");
        return nil;
    }
    
}

//=====================================

+(NSString *)serializerArrar:(NSArray *)array
{
    CJSONSerializer *jsonserializer = [CJSONSerializer serializer];
    
    NSError *error = Nil;
    
    NSData *data = [jsonserializer serializeArray:array error:&error];
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return str;
}

@end
